package net.qiujuer.library.clink.core;

import net.qiujuer.library.clink.utils.CloseUtils;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

/**
 * 公共的数据封装
 * 提供了类型以及基本的长度的定义
 * 一个Packet就代表一份完整的数据
 */
public abstract class Packet<T extends Closeable> implements Closeable {

    private T stream;
    private byte type;  // 标识数据类型，字符串、文件
    protected long length;   // 数据长度

    public long length() {
        return length;
    }

    public byte type() {
        return type;
    }

    protected abstract T createStream();

    protected void closeStream(T stream) throws IOException {
        stream.close();
    }

    public final T open() {
        if (stream == null) {
            stream = createStream();
        }
        return stream;
    }

    @Override
    public final void close() throws IOException {
        if (stream != null) {
            closeStream(stream);
            stream = null;
        }
    }

}
